package com.example.administrator.runbook.findfragment.activity;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.runbook.R;
import com.example.administrator.runbook.findfragment.adapter.FindClassifyAdapter;
import com.example.administrator.runbook.findfragment.adapter.SectionedSpanSizeLookup;
import com.example.administrator.runbook.findfragment.model.ClassifyEvent;
import com.example.administrator.runbook.findfragment.model.FindAllClassify;
import com.example.administrator.runbook.findfragment.model.FindClassify;
import com.example.administrator.runbook.findfragment.model.FindClassifyAllItem;
import com.example.administrator.runbook.findfragment.model.FindClassifyItemAll;
import com.example.administrator.runbook.findfragment.model.MessageToAfterClassify;
import com.example.administrator.runbook.findfragment.network.GetFindClassifyService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class FindClassifyActivity extends BaseActivity implements View.OnClickListener {

    private GetFindClassifyService mGetFindClassifyService;
    private ImageView mWaitAnim;
    private RecyclerView mRecycleView;
    private RelativeLayout mAnimAll;
    private Object mData;
    private List<FindAllClassify> mAllClassifies;
    private Drawable mDrawable;
    private FindClassifyAdapter mClassifyAdapter;
    private List<FindClassifyAllItem> mClassifyAllItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_find_classify);
        mAnimAll = (RelativeLayout) findViewById(R.id.activity_find_classify_wait);
        mWaitAnim = (ImageView) findViewById(R.id.activity_find_classify_wait_img);
        mRecycleView = (RecyclerView) findViewById(R.id.activity_find_classify_RecycleView);
        mAllClassifies = new ArrayList<>();
        mClassifyAllItems = new ArrayList<>();
        mClassifyAdapter = new FindClassifyAdapter(this, mAllClassifies);
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        manager.setSpanSizeLookup(new SectionedSpanSizeLookup(mClassifyAdapter, manager));
        mRecycleView.setLayoutManager(manager);
        mRecycleView.setAdapter(mClassifyAdapter);
        startAnim();
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl("http://api.zhuishushenqi.com");
        builder.addConverterFactory(ScalarsConverterFactory.create());
        builder.addConverterFactory(GsonConverterFactory.create());
        builder.addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.newThread()));
        Retrofit build = builder.build();
        mGetFindClassifyService = build.create(GetFindClassifyService.class);
        getData();
    }

    @Override
    public void setToolBar(Toolbar toolbar) {
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
    }

    @Override
    public void setToolBarTitleText(TextView toolBarTitleText) {
        if (toolBarTitleText != null) {
            toolBarTitleText.setText("分类");
        }
    }

    @Override
    public void setBackImg(ImageView backImg) {
        if (backImg != null) {
            backImg.setOnClickListener(this);
        }
    }

    private void startAnim() {
        mDrawable = mWaitAnim.getDrawable();
        if (mDrawable != null && mDrawable instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mDrawable;
            animationDrawable.start();
        }
    }

    public void getData() {
        Observable<FindClassify> classify = mGetFindClassifyService.getClassify();
        classify.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<FindClassify>() {
                    @Override
                    public void onCompleted() {
                        after();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(FindClassifyActivity.this, "网络不给力", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(FindClassify classify) {
                        List<FindClassify.FindEntry> entryManList = classify.getFindEntryManList();
                        List<FindClassify.FindEntry> entryWomenList = classify.getFindEntryWomenList();
                        List<FindClassify.FindEntry> entryPressList = classify.getFindEntryPressList();
                        mAllClassifies.add(new FindAllClassify("男生", entryManList));
                        mAllClassifies.add(new FindAllClassify("女生", entryWomenList));
                        mAllClassifies.add(new FindAllClassify("出版", entryPressList));
                    }
                });
    }

    private void after() {
        Observable<FindClassifyItemAll> itemAll = mGetFindClassifyService.getClassifyItemAll();
        itemAll.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<FindClassifyItemAll>() {
                    @Override
                    public void onCompleted() {
                        stopAnim();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(FindClassifyActivity.this, "网络不给力", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(FindClassifyItemAll all) {
                        mClassifyAllItems.clear();
                        List<FindClassifyItemAll.ItemAll> manList = all.getItemManList();
                        List<FindClassifyItemAll.ItemAll> womenList = all.getItemWomenList();
                        List<FindClassifyItemAll.ItemAll> pressList = all.getItemPressList();
                        mClassifyAllItems.add(new FindClassifyAllItem("男生", manList));
                        mClassifyAllItems.add(new FindClassifyAllItem("女生", womenList));
                        mClassifyAllItems.add(new FindClassifyAllItem("出版", pressList));
                    }
                });
    }

    private void stopAnim() {
        mDrawable = mWaitAnim.getDrawable();
        if (mDrawable != null && mDrawable instanceof AnimationDrawable) {
            AnimationDrawable animationDrawable = (AnimationDrawable) mDrawable;
            animationDrawable.stop();
        }
        mAnimAll.setVisibility(View.GONE);
        mRecycleView.setVisibility(View.VISIBLE);
        mClassifyAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(ClassifyEvent my){
        //TODO:跳到分类之后的详情界面
        if (my != null) {
            String title = my.getTitle();
            String name = my.getItem().getClassName();
//            int indexOf = mClassifyAllItems.indexOf(title);
//            int of = mClassifyAllItems.get(indexOf).getItemAlls().indexOf(name);
            int indexOf = 0;
            for (int i = 0; i < mClassifyAllItems.size(); i++) {
                if (mClassifyAllItems.get(i).getName().equals(title)) {
                    indexOf = i;
                    break;
                }
            }
            int of = 0;
            for (int i = 0; i < mClassifyAllItems.get(indexOf).getItemAlls().size(); i++) {
                if (mClassifyAllItems.get(indexOf).getItemAlls().get(i).getMajor().equals(name)) {
                    of = i;
                    break;
                }
            }
            List<String> mins = mClassifyAllItems.get(indexOf).getItemAlls().get(of).getMins();
            for (int i = 0; i < mins.size(); i++) {
                Log.d("Hello", "onEvent: " + mins.get(i));
            }
//            Toast.makeText(this, "Title is " + title + " ItemName is " + name + " is Clicked", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, AfterClassifyActivity.class);
            MessageToAfterClassify classify = new MessageToAfterClassify();
            classify.setTitle(title);
            classify.setName(name);
            classify.setMins(mins);
            intent.putExtra(AfterClassifyActivity.MESSAGEINFOR, classify);
            startActivity(intent);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_find_classify_goBack_img:
                finish();
                break;
        }
    }
}
